package flc.ast.activity;


import androidx.annotation.NonNull;
import androidx.annotation.WorkerThread;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.poster.ColorFilter;
import com.stark.poster.DataProvider;
import com.stark.poster.FilterAdapter;
import com.stark.poster.PosterConst;
import com.stark.poster.PosterEntry;
import com.stark.poster.PosterStyle;
import com.stark.poster.PosterTypeAdapter;
import com.stark.poster.databinding.MenuPosterFilterBinding;
import com.stark.poster.lib.Layer;
import com.stark.poster.lib.Model;
import com.stark.poster.lib.OnLayerSelectListener;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.MyPosterAdapter;
import flc.ast.databinding.ActivityPlacardBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.constant.Extra;
import stark.common.basic.utils.AssetUtil;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.WorkPathUtil;

public class PlacardActivity extends BaseAc<ActivityPlacardBinding> {

    private static final int MAX_COVER_WIDTH = 720;
    private static final int MAX_LAYER_WIDTH = 400;
    public static List<String> mPaths;
    private List<PosterStyle> mPosterStyleList = new ArrayList<>();
    private int mStylePos = 0;
    private Layer mSelectedLayer;
    private Dialog myTipDialog;


    @Override
    protected int onCreate() {
        return R.layout.activity_placard;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivPlacardBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivPlacardSave.setOnClickListener(this);
        mPosterStyleList.addAll(DataProvider.getPosterStyle(mPaths.size(), this));
        mDataBinding.rvPlacardList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        MyPosterAdapter myPosterAdapter = new MyPosterAdapter(R.layout.item_placard, mPosterStyleList);
        mDataBinding.rvPlacardList.setAdapter(myPosterAdapter);
        myPosterAdapter.setOnItemClickListener(this);
        setModel();
        //提示弹框
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlacardSave:
                save();
                break;
            //提示弹框
            case R.id.tvDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.tvDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (mStylePos == position) {
            return;
        }
        mStylePos = position;
        mDataBinding.pvPoster.getModelView().setFirstDraw(true);
        setModel();
    }

    @Override
    protected void initData() {
        if (mPaths == null || mPaths.size() == 0) {
            finish();
            return;
        }
        initMenuFilterView();
    }

    private void save() {

        showDialog(getString(R.string.save_pic_ing));
        RxUtil.create(new RxUtil.Callback<Uri>() {

            @Override
            public void doBackground(ObservableEmitter<Uri> emitter) {
                Uri uri = doSave();
                emitter.onNext(uri);
            }

            @Override
            public void accept(Uri uri) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_suc));
                startActivity(HomeActivity.class);
            }
        });
    }

    @WorkerThread
    protected Uri doSave() {
        Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.pvPoster.getModelView());
        Uri saveFileUri = null;
        try {
            String saveFilePath = WorkPathUtil.generateJpgFilePath();
            boolean success = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(saveFilePath));
            if (success) {
                saveFileUri = FileP2pUtil.copyPrivateImgToPublic(this, saveFilePath);
            }
            FileUtils.delete(saveFilePath);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return saveFileUri;
    }

    private void setModel() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                setModel(mStylePos);
                emitter.onNext(true);
            }

            @Override
            public void accept(Boolean obj) {
            }
        });
    }

    private void setModel(int pos) {
        PosterStyle posterStyle = mPosterStyleList.get(pos);
        String maskImage = posterStyle.getMaskImage();
        String backgroundImage = posterStyle.getBackgroundImage();
        List<Layer> layers = new ArrayList<>();
        try {
            Bitmap bitmapMask = null;
            if (!TextUtils.isEmpty(maskImage)) {
                bitmapMask = Glide.with(this).asBitmap()
                        .load(AssetUtil.getFilePath(PosterConst.DIR_POSTER_MASK, maskImage))
                        .submit(MAX_COVER_WIDTH, MAX_COVER_WIDTH)
                        .get();
            }
            Bitmap bitmapBg = Glide.with(this).asBitmap()
                    .load(AssetUtil.getFilePath(PosterConst.DIR_POSTER_BG, backgroundImage))
                    .submit(MAX_COVER_WIDTH, MAX_COVER_WIDTH)
                    .get();

            List<PosterStyle.SubViewInfoBean.ImageViewInfoBean> imageViewInfo = posterStyle.getSubViewInfo().getImageViewInfo();

            int i = 0;
            for (PosterStyle.SubViewInfoBean.ImageViewInfoBean subView : imageViewInfo) {
                Bitmap layerBitMap = Glide.with(this).asBitmap().load(mPaths.get(i)).submit(MAX_LAYER_WIDTH, MAX_LAYER_WIDTH).get();
                Layer layer = new Layer(layerBitMap, 0, subView.getAboveMask() == 1);
                for (String point : subView.getPointArray()) {
                    int[] points;
                    points = getPoint(point);
                    layer.markPoint(points[0], points[1]);
                }
                layer.build();
                i++;
                layers.add(layer);
            }
            Model model = new Model(bitmapBg, layers, bitmapMask);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mDataBinding.pvPoster.setModel(model);
                    mDataBinding.pvPoster.getModelView().setOnLayerSelectListener(onLayerSelectListener);
                }
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public int[] getPoint(String source) {
        int[] target = {0, 0};
        if (source == null) {
            return target;
        }
        try {
            String[] arr;
            arr = source.trim().substring(1, source.length() - 1).split(",");
            target[0] = Math.round(Float.parseFloat(arr[0]));
            target[1] = Math.round(Float.parseFloat(arr[1]));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return target;
    }

    private void initMenuFilterView() {
        MenuPosterFilterBinding menuBinding = MenuPosterFilterBinding.inflate(getLayoutInflater());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        menuBinding.rvFilter.setLayoutManager(layoutManager);

        FilterAdapter filterAdapter = new FilterAdapter();
        filterAdapter.setFilters(ColorFilter.getFilters());
        filterAdapter.setListener(onItemSelectListener);
        menuBinding.rvFilter.setAdapter(filterAdapter);

        mDataBinding.pvPoster.addMenuInit(menuBinding.getRoot(), DensityUtil.getWith(this) - SizeUtils.dp2px(100), SizeUtils.dp2px(60));
    }

    private FilterAdapter.OnItemSelectListener onItemSelectListener = new FilterAdapter.OnItemSelectListener() {
        @Override
        public void selected(float[] filter) {
            if (mSelectedLayer != null) {
                if (filter != null) {
                    Bitmap bitmap = ColorFilter.setColorMatrix(mSelectedLayer.getLayer(), filter, false);
                    mSelectedLayer.setFilterLayer(bitmap);
                } else {
                    mSelectedLayer.clearFilter();
                }
                mDataBinding.pvPoster.getModelView().invalidate();
            }
        }
    };

    private OnLayerSelectListener onLayerSelectListener = new OnLayerSelectListener() {
        @Override
        public void onSelected(Layer layer) {
            mSelectedLayer = layer;
            mDataBinding.pvPoster.showMenu(layer);
        }

        @Override
        public void dismiss(Layer layer) {
            //怕有冲突加额外的判断
            if (mSelectedLayer == layer) {
                mSelectedLayer = null;
                mDataBinding.pvPoster.dismissMenu();
            }
        }
    };

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogTipCancel);
        TextView right = inflate.findViewById(R.id.tvDialogTipRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}